#include <iostream>
#include <string>
#include <cstdlib>
#include <pthread.h>
using namespace std;

class Thread{
public:
    enum ThreadStatus{
        NEW = 0,
        RUNNING,
        EXITED
    };
    typedef void (*func_t)(void*);

public:
    Thread(int num, func_t func, void* args):_func(func),_tid(0),_args(args),_status(NEW) {
        char name[128];
        snprintf(name,sizeof(name),"thread-%d",num);
        _name = name;
    }

    int status() { return _status; }
    string threadname() { return _name; }
    pthread_t threadId()
    {
        if (_status == RUNNING)
            return _tid;
        else
        {
            return 0;
        }
    }

    static void* runHelper(void* args){
        //_func(_args); //静态函数不能直接访问成员变量，这里必须使用静态函数，否则就会有this指针，导致类型不匹配
        Thread* thread = (Thread*)args;
        (*thread)();
    }

   void operator ()()
    {
        if(_func != nullptr) _func(_args);
    }

    void run(){
        int n = pthread_create(&_tid,nullptr,runHelper,this);
        if(n != 0) exit(1);
        _status = RUNNING;
    }

    void join()
    {
        int n = pthread_join(_tid,nullptr);
        if( n != 0)
        {
            std::cerr << "main thread join thread " << _name << " error" << std::endl;
            return;
        }
        _status = EXITED;
    }
    ~Thread()
    {
    }


private:
    string _name;   //线程名（自己测试用，可删）
    pthread_t _tid; //线程ID
    func_t _func;   //用户要线程调用的回调
    void* _args;     //回调的传参
    ThreadStatus _status;


};